global without sharing class PartsLendingApplicationUtil {
    public PartsLendingApplicationUtil(){}
    public PartsLendingApplicationUtil(InstrumentDeliverySyncUtil u){}
    public PartsLendingApplicationUtil(ApexPages.StandardController con){}
    //获取NC出库单号
    @RemoteAction
    public static String backWriteFromNc ( List<Map<String,String>> data ){

        try {
            Map<String,SObject> details = new Map<String,SObject>();
            for ( Map<String,String> m : data  ) {
                String detailId = m.get('subId') ;

                SObject so =  Id.valueOf(detailId).getSobjecttype().newSobject();
                
                SObject oldso = details.get(detailId );
                String outno =(String)m.get('outno');
                   

                so.put('Id', detailId);
                so.put('OutgoingNO__c',oldso == null || oldso.get('OutgoingNO__c') == null  ? outno :  ((String)oldso.get('OutgoingNO__c')).contains(outno) ? oldso.get('OutgoingNO__c') : oldso.get('OutgoingNO__c') +'*'+outno   );
                details.put(detailId, so);
            }
            if(details.isEmpty()) return '没有找到数据';
            if(!details.isEmpty())update details.values();

            return '获取成功!';

        }catch (Exception e) {
            
            return '获取失败:'+e.getMessage();

        }

    }
    //转换数值
    public  static Decimal transDecimal(Object obj ){
        Decimal  defaultVal = 0;
        if(obj == null )return defaultVal;
        if(obj instanceof String){
            String d = String.valueOf(obj).trim();
            try {
                return Decimal.valueOf(d);
            }
            catch (Exception e) {
                return defaultVal;
            }
        
        }
        if(obj instanceof Decimal) return (Decimal)obj;
        return Decimal.valueOf(String.valueOf(obj));
    }
     @RemoteAction
    public static String backWriteAllDataFromNc ( Map<String,Map<String,String>> data ){

        try {
            Map<String,PartsLendingDetails__c> details = new Map<String,PartsLendingDetails__c>();
            Map<String,String> workorderMap = new Map<String,String>();

            for (String detailId : data.keySet()  ) {
                Map<String,String> m  = data.get(detailId);
                //String detailId = m.get('subId') ;
                 SObjectType stype = null;
                try {
                    stype = Id.valueOf(detailId).getSobjecttype();

                }
                catch (Exception e) {
                    continue;
                }

                if(stype == WorkOrderProduct__c.SObjectType ) {
                    workorderMap.put(detailId,m.get('ensureNum') );
                    continue;
                }
                if(stype != PartsLendingDetails__c.SObjectType)continue;

                PartsLendingDetails__c so = new  PartsLendingDetails__c();
                so.Id = detailId;
                String outno = DataUtil.getStringValue(m.get('outno'));

                PartsLendingDetails__c oldso = details.get(detailId );

                so.OutgoingNO__c = oldso == null || oldso.OutgoingNO__c == null  ? outno :  oldso.OutgoingNO__c.contains(outno) ? oldso.OutgoingNO__c : oldso.OutgoingNO__c +'*'+outno   ;

                so.B_WarrantyNo__c =transDecimal(m.get('ensureNum')) ;
                so.B_InvoiceNo__c = transDecimal(m.get('invoiceNum')) ;
                //还回数量 = 还回数量+ 保修数量
                so.B_ReturnNo__c = transDecimal(m.get('returnNum'));//+transDecimal(m.get('ensureNum'));
                so.B_No__c = transDecimal(m.get('lendNum')); 

               // if(detailId == 'a3L0k000000PaV4EAK') System.debug('backWriteAllDataFromNc'+so);
                details.put(detailId, so);
            }
            //转换成借出配件的Id 
            for ( WorkOrderProduct__c wp : [select Id,PartsLendingDetails__c  from WorkOrderProduct__c where Id  in: workorderMap.keySet() ]) {
                PartsLendingDetails__c so = details.containsKey(wp.PartsLendingDetails__c) ? details.get(wp.PartsLendingDetails__c) : new PartsLendingDetails__c();
                so.Id = wp.PartsLendingDetails__c;
                so.B_WarrantyNo__c = so.B_WarrantyNo__c == null ? transDecimal(workorderMap.get(wp.Id)) :  so.B_WarrantyNo__c +transDecimal(workorderMap.get(wp.Id)) ; 
                details.put(wp.PartsLendingDetails__c,so);

            }
            ///再次计算还回数量 = 真实还回 + 保修数量 :
            for (PartsLendingDetails__c pa  : details.values()) {

                if(pa.B_WarrantyNo__c != null && pa.B_ReturnNo__c  != null )pa.B_ReturnNo__c = pa.B_ReturnNo__c - pa.B_WarrantyNo__c;
                //if(pa.B_ReturnNo__c  != null && pa.B_ReturnNo__c < 0 ) throw new DmlException('保修配件未做还回操作!');
            }


            if(details.isEmpty()) return '没有找到数据';
            System.debug(details);
            if(!details.isEmpty())update details.values();

            return '获取成功!';

        }catch (Exception e) {
            
            return '获取失败:'+e.getMessage();

        }

    }
    
    //获取当前用记户所有没有还回的配件的出库情况
    @RemoteAction
    public static Map<String,String> getAllLendings(String userId  ){

        Map<String,String> resMap = new Map<String,String>();
        List<User> ul = [select Id from User where Id=:userId];
        if(ul.isEmpty())resMap.put('msg', '用户异常:'+userId);

        List<String> details = new List<String>();
        for ( PartsLendingDetails__c pad : [select Id from PartsLendingDetails__c where PartsLendingApplication__r.IsSycToNc__c = true 
        and PartsLendingApplication__r.OwnerId=:userId and ( LendingMargin__c != 0 or  B_No__c = 0  or ( OutgoingNO__c = null and Product__c != null ) ) ]) {
            
            details.add(pad.Id);
        }

        for (  WorkOrderProduct__c wp :[select Id from WorkOrderProduct__c where PartsLendingDetails__c in:details and WorkOrder__r.Confirm_NC_issue__c = true  ] ) {
                details.add(wp.Id);
        }
       
        resMap.put('pks',EncodingUtil.urlEncode(String.join(details, '\',\''), 'utf-8') );
        return resMap;

    }
    //将获取的出库单号 回写到 明细上
    @RemoteAction
    public static String backWriteAllFromNc(Map<String,Map<String,String>> data){

        try {

            Map<String,SObject> details = new Map<String,SObject>();
            for (String detailId : data.keySet()  ) {

                Map<String,String> m  = data.get(detailId);
                 SObjectType stype = null;
                try {
                    stype = Id.valueOf(detailId).getSobjecttype();

                }
                catch (Exception e) {
                    continue;
                }
                SObject so = stype.newSObject();
                String outno = DataUtil.getStringValue(m.get('outno'));
                so.put('OutgoingNO__c', outno);
                so.put('Id', detailId) ;
                details.put(detailId, so);

            }

            if(details.isEmpty()) return '没有找到数据';
            System.debug(details);
            if(!details.isEmpty())update details.values();
            return '获取成功!';
            
        }
        catch (Exception e) {
            
             return '获取失败:'+e.getMessage();
        }
    

    }

    //获取没有回写出库单号的所有明细数据 
    @RemoteAction
    public static Map<String,String> getAllDetails(){
        Map<String,String>  resMap  = new Map<String,String> ();
        Set<String> reList = new Set<String>();
        for(PartsLendingDetails__c pa : [select Id from PartsLendingDetails__c where OutgoingNO__c = null and PartsLendingApplication__r.IsSycToNc__c  = true ]){
             if(reList.size() > 100) break;
            reList.add(pa.Id);
           
        }
        for(AccessoryWarrantyDetails__c aw : [select Id from AccessoryWarrantyDetails__c where OutgoingNO__c = null and AccessoryWarranty__r.IsSycToNc__c = true ]){
             if(reList.size() > 100) break;
             reList.add(aw.Id);
            
        }
        resMap.put('total', reList.size()+'');
        resMap.put('pks',EncodingUtil.urlEncode(String.join(new List<String>(reList), '\',\''), 'utf-8') );
        return resMap;
    }

    //获取明细Id 
    @RemoteAction
    public static Map<String,String>   getDetails(String mainId ){
        List<SObject>details  = null;
        Map<String,String>  resMap  = new Map<String,String> ();
        List<WorkOrderProduct__c> wpList = new  List<WorkOrderProduct__c>();
        if(Id.valueOf(mainId).getSObjectType() == PartsLendingApplication__c.SObjecttype){

            PartsLendingApplication__c pa = [select Id ,IsSycToNc__c from PartsLendingApplication__c where Id =:mainId ];


            if(pa.IsSycToNc__c != true ) resMap.put('msg', '还没有同步到NC不能获取!');
            details = [select Id from PartsLendingDetails__c where PartsLendingApplication__c =:mainId ]; 
           
            for (  WorkOrderProduct__c wp :[select Id from WorkOrderProduct__c where PartsLendingDetails__r.PartsLendingApplication__c =:mainId ] ) {
                wpList.add(wp);
            }

        }else if(Id.valueOf(mainId).getSObjectType() == WorkOrder__c.SObjecttype){

            WorkOrder__c pa = [select Id ,Confirm_NC_issue__c from WorkOrder__c where Id =:mainId ];

            if(pa.Confirm_NC_issue__c != true ) resMap.put('msg', '还没有同步到NC不能获取!');
            details = [select Id from WorkOrderProduct__c where WorkOrder__c =:mainId and WarrantyNo__c > 0 ]; 

        }else if(Id.valueOf(mainId).getSObjectType() == AccessoryWarranty__c.SObjecttype){

            AccessoryWarranty__c pa = [select Id ,IsSycToNc__c from AccessoryWarranty__c where Id =:mainId ];

            if(pa.IsSycToNc__c != true ) resMap.put('msg', '还没有同步到NC不能获取!');
            details = [select Id from AccessoryWarrantyDetails__c where AccessoryWarranty__c =:mainId  ]; 
        }

        
        if(details == null || details.isEmpty() ) resMap.put('msg', '没有同步NC的明细数据!');
        if(resMap.get('msg') != null ) return resMap;
        List<String> reList = new List<String >();
        for (SObject s  :details ) {
            reList.add((String)s.get('Id'));
        }
        for (WorkOrderProduct__c s  :wpList ) {
            reList.add(s.Id );
        }
        resMap.put('mainId',mainId);
        resMap.put('pks',EncodingUtil.urlEncode(String.join(new List<String>(reList), '\',\''), 'utf-8') );
        return resMap;
    }

    //确认还回
    Webservice static String comfirmBack(String pId){

        try {
            
            PartsReturn__c pa   = [select Id ,ConfirmReturn__c from PartsReturn__c where Id=:pId ];

            if(pa.ConfirmReturn__c == true) return '已确认还回,不要重复点击!';
            pa.ConfirmReturn__c = true;
            Approval.lock(pa,false);
            update pa;
            return '确认还回成功!';

        }catch (Exception e) {

            return '确认还回失败:'+e.getMessage() + e.getStackTraceString();
        }
        
    }
   
    //通知助理
    Webservice static String  notiAssitant(String pId ){

        try{
            Boolean isworkoder = false;
            SObject so = null;
            if(Id.valueOf(pId).getSobjectType() == PartsLendingApplication__c.SObjecttype ){
                PartsLendingApplication__c pa   = [select Id ,NotificationAssistant__c from PartsLendingApplication__c where Id=:pId ];
                if(pa.NotificationAssistant__c != null ) return '已通知过助理,请不要重复通知!';
                so = pa;
                so.put('NotificationAssistant__c', System.today()) ;
                              
                
            }else if(Id.valueOf(pId).getSobjectType() == PartsReturn__c.SObjecttype){

                 PartsReturn__c pa   = [select Id ,NotificationAssistantTime__c from PartsReturn__c where Id=:pId ];
                if(pa.NotificationAssistantTime__c != null ) return '已通知过助理,请不要重复通知!';
                so = pa;
               
                so.put('NotificationAssistantTime__c', System.today()) ;

            }else if(Id.valueOf(pId).getSobjectType() == WorkOrder__c.SObjecttype ){
                 //验证 是否需要发票申请  审批通过的 发票申请
                Integer invoiceCnt  = [select count() from WorkOrderProduct__c where InvoiceNo__c> 0 and WorkOrder__c =:pId ];

                Integer invoiceApplicationCnt = [select count() from PartsInvoiceApplication__c where RelatedWorkOrder__c=:pId and Status__c in  ('已批准','审批中') ];
                if(invoiceCnt > 0 && invoiceApplicationCnt == 0 ) return '使用配件中存在需要开票的配件,没有找到审批中的配件发票申请,不能通知助理!';


                //验证
                /*

                    提示：
                    UF校准包（存货编码为310030100440）只能以保修形式出库并以技术费的方式开票收取费用！
                    请发起技术费相关的配件发票申请并确保已批准！


                */

                

                Integer cnt = [select count() from WorkOrderProduct__c where Product__r.NCCode__c = '310030100440' and WorkOrder__c =:pId ];

                Integer inoviceCnt = [select count() from PartsInvoiceDetails__c where PartsInvoiceApplication__r.RelatedWorkOrder__c =:pId  and ConfirmationQuantity__c > 0  and Parts__r.NCCode__c = '99001009'];

                if(cnt > 0 && inoviceCnt == 0)return '提示：'+
                    'UF校准包（存货编码为310030100440）只能以保修形式出库并以技术费的方式开票收取费用！'+
                    '请发起技术费相关的配件发票申请并确保已批准！';

                WorkOrder__c pa   = [select Id ,NotificationAssistant__c from WorkOrder__c where Id=:pId ];
                if(pa.NotificationAssistant__c != null ) return '已通知过助理,请不要重复通知!';
                so = pa;
                so.put('NotificationAssistant__c', System.today()) ;
                isworkoder = true;
            }else{

                
                return '通知异常!';
            }

            update so ;
            try {
                if(!isworkoder) Approval.lock(so,false);
            }catch (Exception e) {}
            return '已通知助理成功!';
            

        }catch(Exception e ){

            return '通知助理失败:'+e.getMessage() ;
        }


    }



    /* //工程交接申请审批通过 变更所有人
    public static void changePartsLendingOwner(List<EngineerHandover__c> eList,Map<Id,EngineerHandover__c> oldMap ){

        Set<Id> eset = new Set<Id>();
        for (EngineerHandover__c e  :eList ) {
            EngineerHandover__c old = oldMap.get(e.Id);

            if(e.Status__c == '已批准' && old.Status__c != e.Status__c ){

                eset.add(e.Id);
            }

        }
        if(eset.isEmpty())return;
        List<PartsLendingApplication__c> paList = new List<PartsLendingApplication__c>();
        
        for (HandoverDetails__c hd  :[select Id,TransferLoanApplication__c,TransferLoanApplication__r.OwnerId ,ReceivingPerson__c from HandoverDetails__c where MasterTable__c in:eset ] ) {
            if(hd.TransferLoanApplication__c == null || hd.ReceivingPerson__c == null ||  hd.TransferLoanApplication__r.OwnerId == hd.ReceivingPerson__c)continue;
           PartsLendingApplication__c pa = new PartsLendingApplication__c();
           pa.OwnerId = hd.ReceivingPerson__c ;
           pa.Id = hd.TransferLoanApplication__c;
           paList.add(pa);
        }
        if(!paList.isEmpty())update paList;



    }
    */


    //经销商借出明线的: 借出余量不能超过10 
    public static void partsLendingDetailsLimit(List<PartsLendingDetails__c> pList ){
        
        Set<Id> plas = new Set<Id>();
        Map<Id,Map<String,Decimal>> pMap = new Map<Id,Map<String,Decimal>>();

        Set<Id>details = new Set<Id>();
        for (PartsLendingDetails__c pla : pList ) {

            if(pla.PartsLendingApplication__c != null )plas.add(pla.PartsLendingApplication__c);
            Map<String,Decimal> tmp = pMap.containsKey(pla.PartsLendingApplication__c ) ? pMap.get(pla.PartsLendingApplication__c) : new Map<String,Decimal>();
            if(pla.Product__c != null )tmp.put(pla.Product__c, pla.LendingMargin__c );
            if(!pMap.containsKey(pla.PartsLendingApplication__c))pMap.put(pla.PartsLendingApplication__c, tmp);
            if(pla.Id != null )details.add(pla.Id);

        }
        Map<String,String> pm = new Map<String,String>();

        for ( PartsLendingApplication__c pa  : [select Id ,  OwnerId  from PartsLendingApplication__c where Id in: pMap.keySet()  ]) {
            pm.put(pa.OwnerId,pa.Id  );
        }

        Map<Id,User> uMap = new Map<Id,User>([select Id from User where Id in: pm.keySet() and ClientCode__c != null ]);

        if(uMap.isEmpty()) return ;
        Set<String> pids = new Set<String>();
         Map<String,Decimal> pNm = new Map<String,Decimal>();
        for (Id userId  : uMap.keySet()) {

            if(pm.containsKey(userId)){

                Map<String,Decimal> tmp = pMap.get(pm.get(userId));
                for (String pid  :tmp.keySet() ) {
                    String key = userId +'_'+pid ;
                    Decimal num = pNm.containsKey(key) ? transDecimal(tmp.get(pid))+pNm.get(key) : transDecimal(tmp.get(pid));
                    if(num > 10 ) {
                        pList.get(0).addError('同一配件借出数量不能超过10个');
                        return;
                    }
                    pNm.put(key, num);
                    pids.add(pid);

                }
               
            }
        }
        
        if(pids.isEmpty()) return;

        //没有审批的 
        // for (PartsLendingDetails__c  pld  : [select Id,No__c  ,PartsLendingApplication__r.OwnerId ,Product__c,Product__r.Name  from PartsLendingDetails__c 
        //     where  PartsLendingApplication__r.Status__c != '已批准' 
        //     and Id not in: details and PartsLendingApplication__r.OwnerId in:uMap.keySet() and Product__c in: pids ]) {
        //     String key = pld.PartsLendingApplication__r.OwnerId  +'_'+pld.Product__c  ;


        //      Decimal num = transDecimal(pNm.get(key))+ transDecimal(pld.No__c) ;
        //      pld.B_No__c
        //     if(num > 10 ) {
        //         pList.get(0).addError( pld.Product__r.Name + ' : 同一配件借出数量不能超过10个');
        //         return;
        //     }

        // }

         for (AggregateResult   pld  : [select  sum(B_No__c) total ,  sum(B_ReturnNo__c) r_no  ,  sum(B_InvoiceNo__c) i_no  ,  sum(B_WarrantyNo__c) w_no  , PartsLendingApplication__r.OwnerId ,Product__c,Product__r.Name  from PartsLendingDetails__c 

              where PartsLendingApplication__r.OwnerId in:uMap.keySet()

                and Id not in: details   and Product__c in: pids 

               and  B_No__c > 0 and LendingMargin__c  > 0  

             Group by  PartsLendingApplication__r.OwnerId ,Product__c,Product__r.Name 
            ]) {
            String key = pld.get('OwnerId')  +'_'+pld.get('Product__c')  ;
            
             Decimal appNum  = transDecimal(pld.get('total'))- transDecimal(pld.get('r_no'))- transDecimal(pld.get('i_no')) - transDecimal(pld.get('w_no'));
             if(appNum < 0) appNum = 0;
             Decimal num = transDecimal(pNm.get(key))+appNum ;
            if(num > 10 ) {
                pList.get(0).addError( pld.get('Name') + ' : 同一配件借出数量不能超过10个');
                return;
            }

        }



    }
	//配件还回 反写到借出明细表上
    public static void partsReturnBackToDetails(List<PartsReturn__c> pList ,Boolean isdelete ){
        
        Set<Id>pset = new Set<Id>();
        for ( PartsReturn__c p: pList) {
            if(isdelete || p.NotificationAssistantTime__c != null  )pset.add(p.Id);
        }
        System.debug('partsReturnBackToDetails==>'+pset);
        Set<Id> details = new Set<Id>();

        Set<Id>partsReturns = new Set<Id>();
        for (PartsReturnDetails__c p: [select Parts__c from PartsReturnDetails__c where PartsReturn__c  in:pset ]) {
            if(p.Parts__c != null ){
                details.add(p.Parts__c);
                partsReturns.add(p.Id);
            }
        }
        System.debug('partsReturnBackToDetails==>'+details);

        if(details.isEmpty())return;

        partsReturnBackToDetails(partsReturns, details ,isdelete );
        
    }

    
	public static void partsReturnBackToDetails(List<PartsReturnDetails__c> pList ){

		Set<Id> details = new Set<Id>();
        Map<Id,Boolean> mainIdset = new Map<Id,Boolean>();
        for ( PartsReturnDetails__c p: pList) {
            mainIdset.put(p.PartsReturn__c,false);
        }
        //判断 通知助理后再回写
        for(PartsReturn__c pr : [select Id,NotificationAssistantTime__c from PartsReturn__c where Id in:mainIdset.keySet()]){
            
            mainIdset.put(pr.Id, pr.NotificationAssistantTime__c != null  );
        }
        Set<Id>partsReturns = new Set<Id>();
		for (PartsReturnDetails__c p: pList) {

			if(p.Parts__c != null && mainIdset.containsKey(p.PartsReturn__c) && mainIdset.get(p.PartsReturn__c)  ){
                details.add(p.Parts__c);
                partsReturns.add(p.Id);
            }
		}
		if(details.isEmpty())return;
        partsReturnBackToDetails(partsReturns, details, false );
		
	}

    public static void partsReturnBackToDetails(Set<Id>partsReturns , Set<Id> details,Boolean isdelete){

        Map<Id,Decimal > returnMap = new Map<Id,Decimal>();
        
        //details <Id> 还回明细的 iD 

        //还回明细
        //parts__c 借出明细 所有明细
        if(!isdelete) partsReturns.clear();

        for (PartsReturnDetails__c p :[select Id,Parts__c , ReturnQuantity__c from PartsReturnDetails__c where  Parts__c in: details and Id not in: partsReturns ]) {
            
            if(p.ReturnQuantity__c != null )returnMap.put(p.Parts__c, returnMap.containsKey(p.Parts__c) ? returnMap.get(p.Parts__c)+p.ReturnQuantity__c : p.ReturnQuantity__c );
        }
        
        List<PartsLendingDetails__c> tmp = new List<PartsLendingDetails__c>();
        for (Id detailId  : details) {
            
            tmp.add(new PartsLendingDetails__c(Id =detailId,A_ReturnNo__c = transDecimal(returnMap.get(detailId)) ));

        }
        System.debug('partsReturnBackToDetails==>'+tmp);
        update tmp; 
    }

    public static void workOrderProductBackToDetails(List<WorkOrder__c> wpList,boolean isdelete   ){

        Set<Id>pset = new Set<Id>();
        for ( WorkOrder__c p: wpList) {
            if(isdelete || p.NotificationAssistant__c != null  )pset.add(p.Id);
        }
        System.debug('partsReturnBackToDetails==>'+pset);
        Set<Id> details = new Set<Id>();
        for (WorkOrderProduct__c p: [select PartsLendingDetails__c from WorkOrderProduct__c where WorkOrder__c  in:pset ]) {
            if(p.PartsLendingDetails__c != null )details.add(p.PartsLendingDetails__c);
        }
        System.debug('partsReturnBackToDetails==>'+details);

        if(details.isEmpty())return;
        workOrderProductBackToDetails(details);

    }
    public static void workOrderProductBackToDetails(Set<Id> details ){

        Map<Id,Decimal > invoiceMap = new Map<Id,Decimal>();
        Map<Id,Decimal > warrantyMap = new Map<Id,Decimal>();

        for (WorkOrderProduct__c wp :[select Id,PartsLendingDetails__c , Quantity__c , WarrantyNo__c, InvoiceNo__c from WorkOrderProduct__c where  PartsLendingDetails__c in: details]) {
            
            //if(wp.Quantity__c != null )totalMap.put(wp.PartsLendingDetails__c, totalMap.containsKey(wp.PartsLendingDetails__c) ? totalMap.get(wp.PartsLendingDetails__c)+wp.Quantity__c : wp.Quantity__c );
            if(wp.WarrantyNo__c != null )warrantyMap.put(wp.PartsLendingDetails__c, warrantyMap.containsKey(wp.PartsLendingDetails__c) ? warrantyMap.get(wp.PartsLendingDetails__c)+wp.WarrantyNo__c : wp.WarrantyNo__c );
            if(wp.InvoiceNo__c != null )invoiceMap.put(wp.PartsLendingDetails__c, invoiceMap.containsKey(wp.PartsLendingDetails__c) ? invoiceMap.get(wp.PartsLendingDetails__c)+wp.InvoiceNo__c : wp.InvoiceNo__c );
        }

        List<PartsLendingDetails__c> tmp = new List<PartsLendingDetails__c>();
        for (Id detailId  : details) {
            
            tmp.add(new PartsLendingDetails__c(Id =detailId,A_InvoiceNo__c=transDecimal(invoiceMap.get(detailId)) ,A_WarrantyNo__c=transDecimal(warrantyMap.get(detailId) )));

        }
        update tmp; 

    }
	//配件使用 反写到借出明细上
	public static void workOrderProductBackToDetails(List<WorkOrderProduct__c> wpList  ){

		Set<Id> details = new Set<Id>();
         Map<Id,Boolean> mainIdset = new Map<Id,Boolean>();

        for ( WorkOrderProduct__c p: wpList) {

            mainIdset.put(p.WorkOrder__c,false);
        }
         //判断 通知助理后再回写
        for(WorkOrder__c wo : [select Id,NotificationAssistant__c from WorkOrder__c where Id in:mainIdset.keySet()]){
            
            mainIdset.put(wo.Id, wo.NotificationAssistant__c != null  );
        }
		for (WorkOrderProduct__c wo: wpList) {
			if(wo.PartsLendingDetails__c != null && mainIdset.containsKey(wo.WorkOrder__c) && mainIdset.get(wo.WorkOrder__c)  )details.add(wo.PartsLendingDetails__c);
		}

		if(details.isEmpty())return;
		//Map<Id,Decimal > totalMap = new Map<Id,Decimal>();
		
        workOrderProductBackToDetails(details);

	}
    //发票申请编辑保存 带入客户信用 
    public static void bringToCredit(List<PartsInvoiceApplication__c> appList ){

        Set<Id> accset = new Set<Id>();
        Set<String> companys  = new Set<String>();
        for (PartsInvoiceApplication__c pa: appList ) {
            if(pa.InvoiceAccount__c != null && pa.Company__c != null ){

                accset.add(pa.InvoiceAccount__c);
                companys.add(pa.Company__c);
            }

        }

        if(accset.isEmpty())return;
            // List<AccountCredit__c> accCredit =  ;
            //piva.CreditPeriod__c = accCredit.isEmpty() ? null : accCredit[0].NCCreditDeadline__c;

        Map<String,String> acMap = new Map<String,String>();
        for ( AccountCredit__c ac : [select Id, NCCreditDeadline__c , Company__c,Account__c  from AccountCredit__c where Company__c in:companys and Account__c in:accset ]) {
            acMap.put(ac.Account__c+ac.Company__c, ac.NCCreditDeadline__c);
        }

        for (PartsInvoiceApplication__c pa: appList ) {
            String key = pa.InvoiceAccount__c+pa.Company__c;

            if(acMap.containsKey(key))pa.CreditPeriod__c = acMap.get(key);
        }


    }

    //设置发票 销售主管的共享权限
    public static void partsInvoiceShare(List<PartsInvoiceApplication__c> invoices  ,Set<Id> addUsers ,Set<Id> removeUsers ){
        
        Set<Id> allUsers = new Set<Id>();
        allUsers.addAll(addUsers);
        allUsers.addAll(removeUsers);
        System.debug('partsInvoiceShare==>'+ allUsers);
        Map<Id,Id> userManagerMap = new Map<Id,Id>();
        for (User  u :[select Id ,SubCompanyManager__c  from User where Id in :allUsers and SubCompanyManager__c != null  ] ) {
           if(addUsers.contains(u.Id)){
                addUsers.add(u.SubCompanyManager__c);
                userManagerMap.put(u.Id, u.SubCompanyManager__c);
            }
           if(removeUsers.contains(u.Id )  )removeUsers.add(u.SubCompanyManager__c);
        }
        List<PartsInvoiceApplication__Share> removeList = new List<PartsInvoiceApplication__Share>();
        for ( PartsInvoiceApplication__Share  ps: [select Id,ParentId,UserOrGroupId  from PartsInvoiceApplication__Share where ParentId in:invoices  ]) {
            
            if(addUsers.contains(ps.UserOrGroupId)){

                addUsers.remove(ps.UserOrGroupId);
                continue;
            }
            if(removeUsers.contains(ps.UserOrGroupId)) removeList.add(ps);

        }
        List<PartsInvoiceApplication__Share> addList = new List<PartsInvoiceApplication__Share>();
        if(!addUsers.isEmpty()){
            Map<Id,Set<Id> > pMMap = new  Map<Id,Set<Id> >();
            for ( PartsInvoiceApplication__c pa : invoices) {
                
                if(addUsers.contains(pa.SalesSupervisor__c)){
                    addList.add(new PartsInvoiceApplication__Share(ParentId = pa.Id ,UserOrGroupId=pa.SalesSupervisor__c,AccessLevel='Edit' ) );
                    addUsers.remove(pa.SalesSupervisor__c);
                }

                if(userManagerMap.containsKey(pa.SalesSupervisor__c)) {
                    Set<Id> paset = pMMap.containsKey(userManagerMap.get(pa.SalesSupervisor__c))  ? pMMap.get(userManagerMap.get(pa.SalesSupervisor__c)) : new Set<Id>();
                        paset.add(pa.Id );
                    pMMap.put(userManagerMap.get(pa.SalesSupervisor__c), paset );
                }
            }

            for (Id managerid   :  pMMap.keySet()) {
                for(Id paId : pMMap.get(managerid)){
                    addList.add(new PartsInvoiceApplication__Share(ParentId =paId ,UserOrGroupId=managerid,AccessLevel='Edit' ) );
                }

            }




        }
        if(!removeList.isEmpty())delete removeList;
        if(!addList.isEmpty())insert addList;


    }
    
	//发票申请通过后 反写到使用配件明细上
	public static void partsInvoiceBackToDetails(List<PartsInvoiceApplication__c> appList,Map<Id,PartsInvoiceApplication__c> oldMap  ){

        Set<Id>pIds = new Set<Id>();
        Set<Id>addUsers  = new Set<Id>();
        Set<Id>removeUsers = new Set<Id>();
        List<PartsInvoiceApplication__c> shareList  = new List<PartsInvoiceApplication__c>();

        for ( PartsInvoiceApplication__c pa : appList) {
            PartsInvoiceApplication__c old = oldMap.get(pa.Id);
            //设置发票 销售主管的共享权限
            if(pa.SalesSupervisor__c != null  ){
                if(old.SalesSupervisor__c != null &&  pa.SalesSupervisor__c != old.SalesSupervisor__c ) removeUsers.add(old.SalesSupervisor__c);
                addUsers.add(pa.SalesSupervisor__c );
                shareList.add(pa);
            }
            if(pa.Status__c == '已批准' )pIds.add(pa.Id );
            //发票销售审批验证 销售数量价格必填
            if(pa.Status__c == '审批中(销售已确认)' && pa.Status__c != old.Status__c 
                && [select count() from PartsInvoiceDetails__c where PartsInvoiceApplication__c =:pa.Id and (ConfirmationQuantity__c  = null  or   InvoiceAmount_Saler__c = null ) ] > 0 ){
                pa.addError('请先编辑确认发票配件明细的数量和开票价');
                return;
            }
        }
        if(!shareList.isEmpty())  partsInvoiceShare(shareList,addUsers,removeUsers);
        if(pIds.isEmpty())return;
        List<PartsInvoiceDetails__c> pList = [select Id ,WorkOrederProduct__c,ConfirmationQuantity__c from PartsInvoiceDetails__c where PartsInvoiceApplication__c in:pIds  ];
		Set<Id> details = new Set<Id>();
		Map<Id,Decimal> detailMap =new Map<Id,Decimal>();
		for (PartsInvoiceDetails__c p: pList) {

			if(p.WorkOrederProduct__c != null )detailMap.put(p.WorkOrederProduct__c,p.ConfirmationQuantity__c);

		}

		Map<Id,Decimal > invoiceMap = new Map<Id,Decimal>();
		Map<Id,Decimal > warrantyMap = new Map<Id,Decimal>();
		List<WorkOrderProduct__c> wList = [select Id , Quantity__c,WarrantyNo__c, InvoiceNo__c  from WorkOrderProduct__c where  Id in: detailMap.keySet()];
		for (WorkOrderProduct__c wp : wList ) {
			
			wp.InvoiceNo__c = detailMap.get(wp.Id);
			wp.WarrantyNo__c = wp.Quantity__c -(wp.InvoiceNo__c == null ? 0 : wp.InvoiceNo__c );

		}
		update wList;
		
	}

	///同步借出配件明细
	Webservice static String  syncToNc(String pId ){

		PartsLendingApplication__c pa = [select Id,IsSycToNc__c,ResultMsg__c ,OwnerId,Owner.Name,CreatedDate,ReceivingRemarks__c,Remark__c,
		TerminalClient__r.AccountNumber,TerminalClient__r.Name ,PhysicalDelivery__c,Phone__c,FollowupProcessing__c,DocumentTypes__c,
		InvoicingCustomers__r.AccountNumber,InventoryOrganization__c,InstallmentSale__c 
		 from PartsLendingApplication__c where Id =:pId];

		 if(pa.IsSycToNc__c == true) return '已经同步NC,请不要重复同步!';

		 if(pa.PhysicalDelivery__c == null ) return '请填写:是否实物发货!';
		 if(pa.FollowupProcessing__c == null ) return '请填写:后续处理方式!';
		 if(pa.DocumentTypes__c == null ) return '请填写:下游单据类型!';
		 if(pa.InstallmentSale__c == null ) return '请填写:是否分期销售!';
 
         if(pa.TerminalClient__r.AccountNumber == null ) return 'NC不存在客户:'+pa.TerminalClient__r.Name +',请新增客户档案后进行同步';


         Boolean isDealer = [select ClientCode__c from User where Id=:pa.OwnerId].ClientCode__c != null ;


		  User u = [select Id, EmployeeNumber,ExuserCode__c ,Name from User where Id =:UserInfo.getUserId()];
          String operatorName = u.Name;
         String operator =u.ExuserCode__c;// InstrumentDeliverySyncUtil.getUid(u.EmployeeNumber);

         List<OutdoorBean>  oList = new List<OutdoorBean>();
         Decimal total = 0;
		 for (PartsLendingDetails__c pd  : 
		 	[select Id,Product__r.NCCode__c,No__c from PartsLendingDetails__c where  PartsLendingApplication__c =:pId ] ) {
		 	oList.add(new OutdoorBean(pd,pa,operator,isDealer,operatorName));
		    if(pd.No__c != null )total += pd.No__c  ;

		 }
		 for ( OutdoorBean ob : oList) {
		 	ob.totalnum = String.valueOf(total);
		 }
		 if(oList.isEmpty())return '没有明细数据不能同步!';

		 Map<String ,String > returnMap = syncOutdoor(oList);

		String msg   = returnMap.get('code') == '0' ? 'ok' : returnMap.get('msg') ;

        if(msg != 'ok') return msg ;

        pa.IsSycToNc__c = true ;
        pa.ResultMsg__c = returnMap.get('msg');
        update pa ;

        Approval.lock(pa,false);
        return msg ;

	}


	//同步工单保修配件明细   
	Webservice static String  backSyncToNc(String wId ){


		WorkOrder__c wo = [select Id ,Case__c,Confirm_NC_issue__c ,Technician__c , Technician__r.Name,ResultMsg__c, ReceivingRemarks__c,Remark__c,
        Account__r.AccountNumber,PhysicalDelivery__c,ConsigneePhone__c,FollowupProcessing__c,DocumentTypes__c,
        PartsInvoicingCustomers__r.AccountNumber,InventoryOrganization__c,InstallmentSale__c from WorkOrder__c where Id=:wId];

        if(wo.Confirm_NC_issue__c == true )return '已确认或同步,请不要重复点击!';
        if(wo.PhysicalDelivery__c == null ) return '请填写:是否实物发货!';
         if(wo.FollowupProcessing__c == null ) return '请填写:后续处理方式!';
         if(wo.DocumentTypes__c == null ) return '请填写:下游单据类型!';
         if(wo.InstallmentSale__c == null ) return '请填写:是否分期销售!';

        //验证 是否需要发票申请  审批通过的 发票申请
        Integer invoiceCnt  = [select count() from WorkOrderProduct__c where InvoiceNo__c> 0 and WorkOrder__c =:wId ];

        Integer invoiceApplicationCnt = [select count() from PartsInvoiceApplication__c where RelatedWorkOrder__c=:wId and Status__c = '已批准' ];

        if(invoiceCnt > 0 && invoiceApplicationCnt == 0 ) return '使用配件中存在需要开票的配件,没有找到审批通过的配件发票申请,不能确认或同步!';

		 List<WorkOrderProduct__c>prdList = [select Id ,Product__c ,Product__r.NCCode__c, WarrantyNo__c
		 from WorkOrderProduct__c where WorkOrder__c =:wId and WarrantyNo__c > 0  ];
		 if(prdList.isEmpty()){

            wo.Confirm_NC_issue__c = true;
            update wo;

            return '配件已确认!';
         }

		 User u = [select Id,EmployeeNumber ,ExuserCode__c,Name from User where Id =:UserInfo.getUserId()];
          String operator = u.ExuserCode__c;
          String operatorName = u.Name;
         List<OutdoorBean>  oList = new List<OutdoorBean>();
         Decimal total = 0;
         Boolean isDealer = [select ClientCode__c from User where Id=:wo.Technician__c ].ClientCode__c != null ;

		for ( WorkOrderProduct__c prd : prdList ) {
			oList.add(new OutdoorBean(prd,wo,operator,isDealer,operatorName ));
		    if(prd.WarrantyNo__c != null )total += prd.WarrantyNo__c  ;
		}

		for ( OutdoorBean ob : oList) {
		 	ob.totalnum = String.valueOf(total);
		 }


		 Map<String ,String > returnMap = syncOutdoor(oList);

		String msg   = returnMap.get('code') == '0' ? 'ok' : returnMap.get('msg') ;

        if(msg != 'ok') return msg ;
        wo.Confirm_NC_issue__c = true;
        wo.ResultMsg__c =  returnMap.get('msg');
        update wo;


       	// for (WorkOrderProduct__c prd : prdList ) {
       	// 	prd.IsSycToNc__c = true;
       	// }
        // update prdList ;

        return msg ;

	}
    //同步配件保修到NC迈克电子出库单
    Webservice static String syncAccessoryWarranty(String aId){

        AccessoryWarranty__c aw = [select Id ,CreatedDate,IsSycToNc__c,Owner.Name ,OwnerId,InstallmentSale__c,RelatedWorkOrder__r.InventoryOrganization__c,ResultMsg__c,
        Merchants__r.AccountNumber,Phone__c,PhysicalDelivery__c,FollowupProcessing__c,DocumentTypes__c,Remark__c,ReceivingRemarks__c,IsSycToNcSubCompany__c
         from AccessoryWarranty__c where Id=:aId ];

        if(aw.IsSycToNc__c == true && aw.IsSycToNcSubCompany__c == true ) return '已经同步NC,不要重复点击!';

        if(aw.PhysicalDelivery__c == null ) return '请填写:是否实物发货!';
         if(aw.FollowupProcessing__c == null ) return '请填写:后续处理方式!';
         if(aw.DocumentTypes__c == null ) return '请填写:下游单据类型!';
         if(aw.InstallmentSale__c == null ) return '请填写:是否分期销售!';
         if(aw.RelatedWorkOrder__r.InventoryOrganization__c == null) return '请维护关联工单的申请出库组织!';
        List<AccessoryWarrantyDetails__c> awList = [select Id ,Parts__c,Parts__r.NCCode__c from AccessoryWarrantyDetails__c where AccessoryWarranty__c = : aId];
         User u = [select Id,Name , EmployeeNumber ,ExuserCode__c from User where Id =:UserInfo.getUserId()];
          String operator = u.ExuserCode__c;
          String operatorName = u.Name;
         List<OutdoorBean>  oList = new List<OutdoorBean>();
         Decimal total = 0;
         Boolean isDealer = [select ClientCode__c from User where Id=:aw.OwnerId].ClientCode__c != null ;
        for ( AccessoryWarrantyDetails__c awd : awList ) {
            oList.add(new OutdoorBean(awd ,aw,operator,isDealer,operatorName ));
            total += 1 ;
        }

        for ( OutdoorBean ob : oList) {
            ob.totalnum = String.valueOf(total);
         }

         String msg = ''; 
         // 同步到子公司 电子 
        Map<String ,String > returnMap  = null;
        if(aw.ResultMsg__c == null  )aw.ResultMsg__c = '';
        if(aw.IsSycToNc__c != true ){
            returnMap = syncOutdoor(oList);

            if(returnMap.get('code') != '0' ){
                msg  =' 同步到电子失败:'+ returnMap.get('msg') ;
            }else{
                aw.IsSycToNc__c = true;
                aw.ResultMsg__c +=  returnMap.get('msg');
            }
            //returnMap.get('code') == '0' ? 'ok' : 
            
        }

        

        if(aw.IsSycToNcSubCompany__c != true ){
            for ( OutdoorBean ob : oList) {
                ob.pk_corp = aw.RelatedWorkOrder__r.InventoryOrganization__c; 

                if( ob.applynum != null &&  ob.applynum != '0' && !ob.applynum.contains('-') )ob.applynum = '-'+ob.applynum;
                if( ob.totalnum != null &&  ob.totalnum != '0' && !ob.totalnum.contains('-') )ob.totalnum = '-'+ob.totalnum;
                //ob.nextaction = '库存其他入库单';
             }
            // String msg   = returnMap.get('code') == '0' ? 'ok' : returnMap.get('msg') ;
            // if(msg != 'ok') return msg ;            //同步到子公司
            returnMap = syncOutdoor(oList);
            if(returnMap.get('code') != '0' ){
                msg  = ' 同步到子公司失败:'+returnMap.get('msg') ;
            }else{
                 aw.IsSycToNcSubCompany__c = true;
                aw.ResultMsg__c +=  returnMap.get('msg');
            }

           
        }
            
        if(aw.ResultMsg__c.length()> 255) aw.ResultMsg__c = aw.ResultMsg__c.substring(0, 254);
        update aw;
        if(String.isBlank(msg)) msg = '同步成功!';
       return msg ;
    }
    //发票明细同步NC报价单 同时反写到价目表
    Webservice static String syncInvoiceDetail(String pId ){
            
        PartsInvoiceApplication__c pa = [select WhetherReverse__c,Status__c, OwnerId,Id,Name,IsSycToNc__c,InvoiceAccount__c, RelatedWorkOrder__r.InventoryOrganization__c ,Owner.Name ,
            InventoryOrganization__c ,InvoiceAccount__r.AccountNumber  from PartsInvoiceApplication__c where Id=:pId];
        if(pa.Status__c != '已批准') return '配件发票申请'+pa.Status__c +',不能同步!';
        if( pa.IsSycToNc__c == true && pa.WhetherReverse__c ==true  )return '已经同步NC,不要重复点击!';
        User u = [select Id, Manager.Name from User where Id =:pa.OwnerId];
        List<ContractWebService.ConProductArgs> conProductArgsList = new List<ContractWebService.ConProductArgs>();
        Map<String,String> salesMap = ImportObject.getPicklistValues('PriceList__c', 'SalesCode__c', false);
        Map<String,String > companyMap = ImportObject.getPicklistValues('Contract__c', 'CorpCode__c', true);

        String salescode = salesMap.get(companyMap.get(pa.InventoryOrganization__c));
        Set<Id> prodsets = new Set<Id>();
         List<PartsInvoiceDetails__c>padList = [select Id,Parts__r.NCCode__c,Parts__c , ConfirmationQuantity__c,InvoiceAmount_Saler__c  from PartsInvoiceDetails__c where PartsInvoiceApplication__c=:pId and ConfirmationQuantity__c > 0  ];
        for (PartsInvoiceDetails__c pad  :padList) {
           
              
                ContractWebService.ConProductArgs cpa = new ContractWebService.ConProductArgs();
                cpa.corpcode =  pa.InventoryOrganization__c  ;  //公司编码
                cpa.custcode =  pa.InvoiceAccount__r.AccountNumber ;  //客户编码

                cpa.vsalestrucode =salescode;//cp.Contract__r.Vsalestrucode__c ; //销售组织编码

                if( cpa.vsalestrucode == null ) return '请维护公司信息!';

                cpa.created_by = pa.Owner.Name; //创建人名字
                cpa.sub_corp_manager = u.Manager.Name;  //报价的销售中心总监名字
                cpa.csourcecode = pa.Name; //合同自动编号
                cpa.ts = Utils.date2string(System.now()) ; //合同的lastmodifieddate
                cpa.cemployeecode = pa.Owner.Name; //所有者
                cpa.invcode = pad.Parts__r.NCCode__c; //产品的NCCode__c
                cpa.dreceiptdate  = Utils.date2string(Date.valueOf(System.now()));//报价日期
                cpa.noriginalcurtaxprice = String.valueof(pad.InvoiceAmount_Saler__c)  ; //SalesPrice__c
                cpa.nitemdiscountrate = '100';//默认100
              //  cpa.nnumber = String.valueof(cp.Number__c);
                cpa.opertype = '1';//'t; //操作类型   1=新增  2=修改  3=删除
                cpa.quotetype = '1'; //报价类型   1=报价  2=调价
                cpa.csalequotationid = pa.Id ;
                cpa.csalequotation_bid =pad.Id;
                cpa.currtypename = '人民币';
               //if(cp.Contract__r.TerminalCustomer__r.NCICCode__c != null ) cpa.addCustomer =cp.Contract__r.TerminalCustomer__r.NCICCode__c;

                conProductArgsList.add(cpa);
                prodsets.add(pad.Parts__c);
              
        }

        if(pa.IsSycToNc__c != true  ){
             String msg = ContractWebService.sycToNcNew(conProductArgsList); 
            pa.Result__c = msg == null ? null : msg.length() > 255 ? msg.substring(0, 254) : msg ;
            
            pa.IsSycToNc__c = true;
            update pa;
        }
        if(pa.WhetherReverse__c == true  )return '同步成功并反写到价目表!';
        //反写价目表
        Map<String,PriceList__c> priceListMap = new Map<String,PriceList__c>();
        for (PriceList__c p :[select Id ,ApplicableCustomers__c,Product__c,Price__c,SalesCode__c  from PriceList__c where  Account__c =:pa.InvoiceAccount__c 
         and  SalesCode__c =:salescode and Product__c in:prodsets ] ) {
            
              priceListMap.put(p.Product__c+'-'+p.SalesCode__c+'-'+p.ApplicableCustomers__c ,p);   

        }
         

        SavePoint sp = Database.setSavepoint();
        try {
        List<PriceList__c> plList = new List<PriceList__c>();
            String terminalId = pa.InvoiceAccount__c;

            for (PartsInvoiceDetails__c pad: padList) {

                 PriceList__c pl = null;
                 String key = pad.Parts__c +'-'+salescode+ '-'+terminalId ;
                if(priceListMap.containsKey(key)){

                    pl = priceListMap.get(key);

                }else{

                    pl = new PriceList__c();
                    pl.Product__c = pad.Parts__c;
                    pl.SalesCode__c = salescode;
                    pl.Account__c =pa.InvoiceAccount__c;
                    pl.Company__c = companyMap.get(pa.RelatedWorkOrder__r.InventoryOrganization__c);
                    pl.ApplicableCustomers__c = terminalId;

                }
             
                  pl.Price__c =  pad.InvoiceAmount_Saler__c ;
                  pl.OwnerId = pa.OwnerId;

                  plList.add(pl);

            }
            System.debug('+++'+plList);
            
           if(plList.size() >0) upsert plList;
          
            pa.WhetherReverse__c = true;
            update pa;
            return '同步成功,并反写到价目表!';

        }catch (Exception e) {
            Database.rollback(sp);
            return '同步成功!写入到价目表错误:'+e.getMessage();
        }
                


    }


	 public static  Map<String,String > syncOutdoor(List<OutdoorBean> outdoorList){
        Map<String,String > returnMap = new Map<String,String>();
        returnMap.put('code', '1');//失败;

        String url = Label.NCLrckInterface;

            Map<String,Object> data = new Map<String,Object>();
            data.put('data', outdoorList);

            HttpRequest req = new HttpRequest();
            req.setMethod('POST');
            req.setBody(JSON.serialize(data) );
            System.debug(JSON.serialize(data));
            req.setHeader('Content-Type','text/plain');
            //req.setHeader('Content-Type','application/x-www-form-urlencoded ; charset=utf-8');
            req.setEndpoint(url);
            HttpResponse res = Utils.postRequest(req, 1);
            String sycmsg = '';
             ///返回结果处理
            if (res.getStatusCode() == 200) {
                System.debug(res.getBody());
                Map<String,Object> r = null;
                  //如果是测试
                    if(Test.isRunningTest()){
                        Map<String,Object>  resBody= new Map<String,Object>();
                        resBody.put('code','0');
                        resBody.put('result','{\"result_msg\":\"UPT40088-000001\",\"result\":1}');
                        r =  resBody;
                    }else{
                        r= (Map<String,Object> ) JSON.deserializeUntyped(res.getBody());
                    }
              if(r.get('code') == 0 || r.get('code') == '0'){
                    Map<String,Object> rs = (Map<String,Object>) JSON.deserializeUntyped(((String)r.get('result')));
                    
                  if( (rs.get('result') == 1 || rs.get('result') == '1' ) ){
                        
                        returnMap.put('code', '0');
                        sycmsg = String.valueOf(r.get('result'));

                   }else{
                        sycmsg = '同步借出配件申请失败 : '+rs.get('result_msg');
                   }

                }else{

                    sycmsg = '同步借出配件申请失败 : '+String.valueOf(r.get('msg'));
                }

            }else{
                 sycmsg = '同步借出配件申请失败 : '+res.getBody();
            }
            returnMap.put('msg', sycmsg);
            return returnMap ;

    }
    public class OutdoorBean{

        //public String approver;//审批人

        public String  cbizid ;

        //public String cdptid;

        public String dbilldate ;
        public String operator;
        public String pk_corp; 

        public String  pk_org_id ;
        public String vnote;
        public String totalnum ;
        public String recvnotes;
        public String isentity; 

        public String  cgphone ;
        public String nextaction;
        public String nextbilltype ;
        public String custcode;
        public String invcode; 

        public String  ts ;
        public String sapply_hid;
        public String sapply_bid ;
        public String applynum;
        public String zdcode;
        public String planrecivedate;//计划领用日期
        public String isInstallsale;//是否分期销售
        public String sfmanid;
        public String sflistid;

        public OutdoorBean(PartsLendingDetails__c pd,PartsLendingApplication__c pa ,String opr,Boolean isDealer ,String oprName){
        	cbizid = isDealer ? oprName :  pa.Owner.Name ;
        	dbilldate = System.now().format('yyyy-MM-dd');//pa.CreatedDate.format('yyyy-MM-dd');
        	planrecivedate = System.now().format('yyyy-MM-dd');
            operator =  opr ;
            pk_corp = pa.InventoryOrganization__c ;//corpcode;
            //vnote = np.Remarks__c;
            totalnum = '0';
            recvnotes = pa.ReceivingRemarks__c ;
            vnote = pa.Remark__c ;
            zdcode = pa.TerminalClient__r.AccountNumber == null ? '' : pa.TerminalClient__r.AccountNumber  ;
            isentity = pa.PhysicalDelivery__c;

            cgphone = pa.Phone__c;
            nextaction = pa.FollowupProcessing__c ;
            nextbilltype =  pa.DocumentTypes__c ;
            custcode = pa.InvoicingCustomers__r.AccountNumber;

            invcode = pd.Product__r.NCCode__c;

            ts = System.now().format('yyyy-MM-dd HH:mm:ss');

            sapply_hid = pa.Id;

            sapply_bid = pd.Id;
            sfmanid = pa.Id;
            sflistid = pd.Id;

            isInstallsale = '否';

            applynum = String.valueOf(pd.No__c);



        } 
         public OutdoorBean(AccessoryWarrantyDetails__c pd,AccessoryWarranty__c pa ,String opr ,Boolean isDealer ,String oprName ){
           //DocumentTypes__c','FollowupProcessing__c','Remark__c',
            //    'Merchants__c','Phone__c','ReceivingRemarks__c','InstallmentSale__c','PhysicalDelivery__c'

            cbizid = isDealer ? oprName : pa.Owner.Name ;
            dbilldate =System.now().format('yyyy-MM-dd');// pa.CreatedDate.format('yyyy-MM-dd');
            planrecivedate = System.now().format('yyyy-MM-dd');
            operator =  opr ;
            pk_corp = 'MKDZ' ;//corpcode;
            vnote = pa.Remark__c;
            totalnum = '0';
            recvnotes =  pa.ReceivingRemarks__c;
            zdcode = pa.Merchants__r.AccountNumber == null ? '' : pa.Merchants__r.AccountNumber  ;
            isentity = pa.PhysicalDelivery__c;

            cgphone = pa.Phone__c;
            nextaction = pa.FollowupProcessing__c ;
            nextbilltype =  pa.DocumentTypes__c ;
            custcode = pa.Merchants__r.AccountNumber == null ? '' : pa.Merchants__r.AccountNumber  ;

            invcode = pd.Parts__r.NCCode__c;

            ts = System.now().format('yyyy-MM-dd HH:mm:ss');

            sapply_hid = pa.Id;

            sapply_bid = pd.Id;

            sfmanid = pa.Id;
            sflistid = pd.Id;
            isInstallsale = '否';

            applynum ='1';


        } 

        public OutdoorBean(WorkOrderProduct__c pd,WorkOrder__c pa ,String opr ,Boolean isDealer,String oprName ){
        	
            cbizid = isDealer ? oprName : pa.Technician__r.Name ;
        	dbilldate = System.now().format('yyyy-MM-dd');
        	planrecivedate = System.now().format('yyyy-MM-dd');
            operator =  opr ;
            pk_corp = pa.InventoryOrganization__c ;//corpcode;
            //vnote = np.Remarks__c;
            totalnum = '0';
            recvnotes = pa.ReceivingRemarks__c ;
            vnote = pa.Remark__c ;
            zdcode = pa.Account__r.AccountNumber == null ? '' : pa.Account__r.AccountNumber  ;
            isentity = pa.PhysicalDelivery__c;

            cgphone = pa.ConsigneePhone__c;
            nextaction = pa.FollowupProcessing__c ;
            nextbilltype =  pa.DocumentTypes__c ;
            custcode = pa.PartsInvoicingCustomers__r.AccountNumber;

            invcode = pd.Product__r.NCCode__c;

            ts = System.now().format('yyyy-MM-dd HH:mm:ss');

            sapply_hid = pa.Id;

            sapply_bid = pd.Id;
             sfmanid = pa.Id;
            sflistid = pd.Id;
            isInstallsale = '否';

            applynum = String.valueOf(pd.WarrantyNo__c );


        } 
        /*
			sfmanid
sflistid 
approver    否   string  审批人 （工号）

cbizid  否   string  申请人 （名字）

cdptid  否   string  申请人部门（编码）

dbilldate   否   string  单据日期

operator    否   string  制单人 （工号）

pk_corp 否   string  公司 （编码）
pk_org_id   否   string  库存组织 （编码）
vnote   是   string  备注
totalnum    是   string  总数量
recvnotes   否   string  收货信息备注
isentity    否   string  是否实物发货（是/否）
cgphone 否   string  收货人联系方式
nextaction  否   string  后续处理方式
nextbilltype    否   string  下游单据类型
custcode    否   string  客商（ID）
invcode 否   string  存货ID
ts  否   string  时间戳
sapply_hid  否   string  表头ID
sapply_bid  否   string  表体ID
appl
        */

    } 
}